package learn.netty.nio;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @USER white
 * @DATETIME 2020/10/17 10:29
 */
public class FileChannelDemo {

    //文件拷贝
    public void fileCopy() throws IOException {
        FileChannel in = new FileInputStream(new File("")).getChannel();
        FileChannel out = new FileOutputStream(new File("")).getChannel();
        out.transferFrom(in, 0, in.size());
    }

    public void directBuffer() throws IOException {
        //channel.map方法 跳过磁盘到内核的拷贝，直接磁盘到用户空间
        ByteBuffer allocate = MappedByteBuffer.allocate(11);
        RandomAccessFile randomAccessFile = new RandomAccessFile("", "");
        FileChannel channel = randomAccessFile.getChannel();
//        FileChannel.MapMode.READ_WRITE 缓冲区的修改会写入文件
//        FileChannel.MapMode.PRIVATE 可读写，修改内容不写入文件
//        FileChannel.MapMode.READ_ONLY 只读
        MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
        buffer.put(new byte[1]);
        buffer.force();//写入文件
    }
}
